<template>
  <a-modal title="中药" :width="1000" :visible="visible" @ok="submit" @cancel="cancelAdd">
    <a-form :form="form">
      <!-- <a-row :gutter="24">
        <a-col :span="4">
          <a-form-item label="图片识别">
            <a-upload list-type="picture-card" class="avatar-uploader" :show-upload-list="false"
              action="https://zhongyi.weizi000.cn/admin/uploadFilejt" :before-upload="beforeUpload" :data="formData"
              @change="handleChange">
              <img style="width: 100%" v-if="imageUrl" :src="imageUrl" alt="avatar" />
              <div v-else>
                <a-icon :type="loading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">添加</div>
              </div>
            </a-upload>
          </a-form-item>
        </a-col>
        <a-col :span="20">
          <a-form-item label="识别到到文字">
            <a-textarea auto-size style="width: 100%;min-height: 100px;" v-model="shibie" placeholder="" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-divider /> -->
      <a-row :gutter="24">
        <a-col :span="24">
          <a-form-item label="名称">
            <a-input v-decorator="['name',{ rules: [{ required: true, message: '请输入名称' }] }]" placeholder="" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="首字母拼音">
            <a-input v-decorator="['pinyin',{ rules: [{ required: true, message: '请输入首字母拼音' }] }]" placeholder="" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="每克价格">
            <a-input v-decorator="['price',{ rules: [{ required: true, message: '请输入价格' }] }]" placeholder="" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="医生指数">
            <a-input v-decorator="['jhprice',{ rules: [{ required: true, message: '请输入医生指数' }] }]" placeholder="" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="进货价">
            <a-input v-decorator="['supplyprice',{ rules: [{ required: true, message: '请输入进货价' }] }]" placeholder="" />
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="药店">
            <a-select @popupScroll="handlePopupScroll" ref="select"
              v-decorator="['pharmacyid',{ rules: [{ required: true, message: '请选择药店' }] }]">
              <a-select-option :value="item.id" v-for='(item,index) in pharmacysOptions'
                :key='index'>{{item.name}}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>

<script>
  import {
    chineseMedicineAdd,
    chineseMedicineUpdate
  } from '@/api/medicine'

  import {
    pharmacysList
  } from '@/api/pharmacys'

  import {
    getFormData
  } from '@/utils/aliOss/aliossUpload.js'
  import aliOssConfig from '@/utils/aliOss/config'


  const formItemLayout = {
    labelCol: {
      span: 4
    },
    wrapperCol: {
      span: 8
    },
  };
  const formTailLayout = {
    labelCol: {
      span: 4
    },
    wrapperCol: {
      span: 8,
      offset: 4
    },
  };

  export default {
    props: {
      visible: {
        type: Boolean,
        required: true,
      }
    },
    data() {
      return {
        shibie: '',
        fileList: [],
        checkNick: false,
        formItemLayout,
        formTailLayout,
        form: this.$form.createForm(this),
        loading: false,
        imageUrl: '',
        formData: {},
        aliOssConfig: aliOssConfig,
        id: 0,
        updateflag: false,
        pPageNo: 1,
        pharmacysOptions: [],
        totalCount: 1
      };
    },
    created() {},
    mounted() {
      this.getPharmacysList()
    },
    methods: {
      handlePopupScroll(e) {
        const {
          target
        } = e
        const scrollHeight = target.scrollHeight - target.scrollTop
        const clientHeight = target.clientHeight
        // 下拉框不下拉的时候
        if (scrollHeight === 0 && clientHeight === 0) {
          this.scrollPage = 1
        } else {
          // 当下拉框滚动条到达底部的时候
          if (scrollHeight < clientHeight + 5) {
            this.scrollPage = this.scrollPage + 1
            const scrollPage = this.scrollPage // 获取当前页
            const totalCount = this.totalCount * (scrollPage || 1) // 新增数据量
            const newData = [] // 存储新增数据
            let max = "" // max 为能展示的数据的最大条数
            if (this.pharmacysOptions.length > totalCount) {
              // 如果总数据的条数大于需要展示的数据
              max = totalCount
            } else {
              // 否则
              max = this.pharmacysOptions.length
            }
            if (this.pharmacysOptions.length < this.totalCount) {
              this.pPageNo++
              this.getPharmacysList()
            }
          }
        }
      },

      getPharmacysList() {
        pharmacysList({
          pageNo: this.pPageNo,
          pageSize: 20
        }).then(res => {
          let test = []
          this.pharmacysOptions = [...this.pharmacysOptions, ...res.data.data]
          this.totalCount = res.data.totalCount
        })
      },

      cancelAdd() {
        this.updateflag = false
        this.$emit('cancel', true)
        this.form.resetFields()
        this.fileList = []
        this.imageUrl = ''
        this.visible = false
      },
      setUpdate(formValue) {
        var that = this
        that.form.setFieldsValue({
          ...formValue
        })
        this.id = formValue.id
        this.updateflag = true
      },
      submit() {
        var that = this
        const {
          form: {
            validateFields
          },
        } = this

        validateFields((errors, values) => {
          if (!errors) {
            values.price = parseFloat(values.price)
            values.jhprice = parseFloat(values.jhprice)
            values.supplyprice = parseFloat(values.supplyprice)
            values.pharmacyid = parseInt(values.pharmacyid)

            if (this.updateflag) {
              values.id = this.id
              chineseMedicineUpdate({
                ...values,
              }).then((res) => {
                if (res.code == 0) {
                  this.fileList = []
                  this.imageUrl = ''
                  that.form.resetFields()
                  that.$emit('ok')
                }
              })
            } else {
              chineseMedicineAdd({
                ...values,
              }).then((res) => {
                if (res.code == 0) {
                  this.fileList = []
                  this.imageUrl = ''
                  that.form.resetFields()
                  that.$emit('ok')
                }
              })
            }
          }
        })
      },
      beforeUpload(file) {
        this.formData = getFormData()
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
        if (!isJpgOrPng) {
          this.$message.error('请上传图片类型文件!')
        }
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isLt2M) {
          this.$message.error('图片最大体积为2MB!')
        }
        return isJpgOrPng && isLt2M
      },
      check() {
        this.form.validateFields(err => {
          if (!err) {
            console.info('success');
          }
        });
      },
      handleChange(info) {
        if (info.file.status === 'uploading') {
          this.loading = true
          return
        }
        if (info.file.status == 'done') {
          this.loading = false
          this.shibie = info.file.response.data
          let reader = new FileReader()
          reader.readAsDataURL(info.file.originFileObj) //把目标文件转地址，文件来自于上传组件。
          let that = this
          reader.onload = function() {
            that.imageUrl = reader.result
          }
        }
      },
      handleImgChange(info) {
        var that = this;
        const isJpgOrPng = info.file.type === 'image/jpeg' || info.file.type === 'image/png'
        if (!isJpgOrPng) {
          this.$message.error('您只能上传图片类型文件!')
          return
        }
        const isLt2M = info.file.size / 1024 / 1024 < 1

        if (!isLt2M) {
          this.$message.error('图片必须小于 1MB!')
          return
        }

        if (info.file.status == "done") {
          info.fileList[info.fileList.length - 1].url = that.aliOssConfig.uploadUrl + '/' + that.formData.key;
        }

        this.fileList = info.fileList

      },
    },
  };
</script>